<template>
  <el-form
    :inline="true"
    ref="formsRef"
    :model="forms"
    :rules="rulesForm"
    label-width="126px"
    class="demo-form-inline"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <!-- 产品检验单编码 -->
        <el-form-item label="产品检验单编码" prop="productInspectionCode">
          <el-input
            v-model="forms.productInspectionCode"
            readonly
            @click="selectIdChange"
            :disabled="forms.productReceiveId || forms.status === 1"
            placeholder="选择产品检验单编码"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 产成品入库日期 -->
        <el-form-item label="产成品入库日期" prop="productReceiveDate">
          <el-date-picker
            v-model="forms.productReceiveDate"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled="forms.productReceiveId || forms.status === 1"
            placeholder="请选择产成品入库日期"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 产成品入库单编码 -->
        <el-form-item label="产成品入库单编码" prop="productReceiveCode">
          <el-input
            v-model.trim="forms.productReceiveCode"
            disabled
            placeholder="请输入产成品入库单编码"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 仓库 -->
        <el-form-item label="仓库" prop="warehouseId">
          <el-select
            v-model="forms.warehouseId"
            clearable
            :disabled="forms.productReceiveId || forms.status === 1"
            placeholder="请选择仓库"
            style="width: 100%"
          >
            <el-option
              v-for="wareHouse in wareHouseOptions"
              :key="wareHouse.id"
              :label="wareHouse.warehouseName"
              :value="wareHouse.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="forms.remark"
            placeholder="请输入备注"
            type="textarea"
            maxlength="200"
            show-word-limit
            :disabled="forms.productReceiveId || forms.status === 1"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-divider style="margin: 10px 0"></el-divider>
  <el-button
    style="margin-bottom: 10px"
    type="primary"
    :disabled="forms.productReceiveId || forms.status === 1"
    @click="addRow"
    ><i class="el-icon-plus"></i>添加一行</el-button
  >
  <!-- 添加 仓库 存货名称 -->
  <el-form
    ref="formsTableRef"
    :model="addProductReceiveOrderDetails"
    label-width="140px"
    class="demo-ruleForm"
  >
    <el-table
      border
      :data="addProductReceiveOrderDetails"
      ref="inspectionTableRef"
      class="table v-table"
      style="width: 100%"
    >
      <!-- 序号列 -->
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="仓库">
        <template #default="scope">
          <!--表格里面嵌套表单-->
          <!-- 仓库 -->
          <el-form-item
            :prop="scope.$index + `.warehouseId`"
            class="not-need-form"
          >
            <el-select
              v-model="addProductReceiveOrderDetails[scope.$index].warehouseId"
              :disabled="forms.productReceiveId || forms.status === 1"
              placeholder="请选择仓库"
              filterable
              @change="(value) => handleSelectChange(value, scope.$index)"
            >
              <el-option
                v-for="item in wareHouseOptions"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 存货名称 -->
      <el-table-column label="存货名称">
        <template #default="scope">
          <el-form-item
            :prop="scope.$index + `.inventoryId`"
            class="not-need-form"
            :rules="{
              required: true,
              message: '存货名称不能为空',
              trigger: ['change', 'blur'],
            }"
          >
            <el-select
              v-model="addProductReceiveOrderDetails[scope.$index].inventoryId"
              placeholder="请选择存货名称"
              :disabled="forms.productReceiveId || forms.status === 1"
              filterable
            >
              <el-option
                v-for="item in inventoryNameOption"
                :key="item.id"
                :label="item.inventoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 数量 -->
      <el-table-column label="数量">
        <template #default="scope">
          <el-form-item
            :prop="scope.$index + `.quantity`"
            class="not-need-form"
            :rules="[
              {
                required: true,
                message: '数量不能为空',
                trigger: ['blur'],
              },
              {
                validator: validatePositiveInteger,
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input
              v-model.trim="
                addProductReceiveOrderDetails[scope.$index].quantity
              "
              style="width: 100%"
              type="number"
              :min="0"
              placeholder="请输入数量"
              :disabled="forms.productReceiveId || forms.status === 1"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="60">
        <template #default="scope">
          <el-button
            @click="
              handleDeleteRow(addProductReceiveOrderDetails[scope.$index])
            "
            type="text"
            style="color: #f54346"
            :disabled="forms.productReceiveId || forms.status === 1"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-form>

  <!-- 审核弹框选择产品检验单编码 -->
  <dialog-com
    ref="selProductInspectionIdRef"
    :title="'产品检验单编码'"
    width="80%"
    @confirm-change="confirmSelectProductInspectionChange"
    @close-change="closeSelectDocumentChange"
  >
    <template #content>
      <div style="margin-bottom: 10px">
        <el-input
          v-model="productInspectionCode"
          clearable
          style="width: 200px"
          placeholder="产品检验单编码"
        />
        <el-button
          type="primary"
          :icon="Search"
          style="margin-left: 10px"
          @click="queryProductInspectionIdChange"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
      </div>
      <data-table
        ref="productInspectionTableRef"
        :tableKey="documentIdTableKey"
        @table-selection-change="productInspectionIdSelectionChange"
      >
        <template #status="{ row }">
          <el-tag :type="getAuditStatus(row.status).type">
            {{ getAuditStatus(row.status).info }}</el-tag
          >
        </template>
      </data-table>
      <!-- 分页 -->
      <div class="table-pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :page-sizes="[15, 30, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>
  </dialog-com>

</template>

<script>
import {
  getProductInspectionOrderList,
  getProductReceiveOrderInfo,
} from "@/api/productionManagement/finishedProductWarehouseReceipt.js";

export default {
  props: {},
  components: {
  },
  data() {
    return {
      forms: {},
      rulesForm: {
        productInspectionCode: [
          { required: true, message: "请选择产品检验单编码", trigger: "blur" },
        ],
        productReceiveDate: [
          {
            type: "date",
            required: true,
            message: "请选择产成品入库日期",
            trigger: "change",
          },
        ],
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
      },
      wareHouseOptions: [],
      inventoryNameOption: [],
      addProductReceiveOrderDetails: [],
      productInspectionCode: "",
      currentPage: 1,
      pageSize: 15,
      totalPage: 0,
      documentIdTableKey: [
        {
          value: "productInspectionCode",
          name: "产品检验订单编号",
          minWidth: "250",
          sortable: false,
        },
        {
          value: "inventoryName",
          name: "存货名称",
          minWidth: "250",
        },
        { value: "productInspectionTime", name: "检验时间", minWidth: "250" },
        {
          value: "inspectionName",
          name: "抽检人名称",
          minWidth: "120",
        },
        {
          value: "status",
          name: "单据状态",
          minWidth: "150",
          slot: true,
        },
        {
          value: "remark",
          name: "备注",
          minWidth: "250",
        },
      ],
      selectProductInspectionId: [],
    };
  },
  created() {},
  mounted() {},
  methods: {
    validatePositiveInteger(rule, value, callback) {
      if (value === "" || value === null || value === undefined) {
        callback();
        return;
      }
      // 检查是否为数字
      if (isNaN(value)) {
        callback(new Error("数量必须为数字"));
        return;
      }
      // 转换为数字
      const numValue = Number(value);
      // 检查是否为正整数
      if (!Number.isInteger(numValue)) {
        callback(new Error("数量必须为整数"));
        return;
      }
      if (numValue < 0) {
        callback(new Error("数量不能为负数"));
        return;
      }
      callback();
    },
    // 调整状态显示文案和样式
    getAuditStatus(val) {
      // 1 审核通过   0 审核不通过    null 未审核
      // 目前只有三种状态 对象最后一个元素代表null的状态，后续有新增请在对应的倒数第二个位置添加
      const typeObj = {
        0: "danger",
        1: "primary",
        2: "warning",
      };
      const infoObj = {
        0: "审核失败",
        1: "审核成功",
        2: "未审核",
      };
      return {
        type:
          val !== null
            ? typeObj[val]
            : typeObj[Object.keys(typeObj)[Object.keys(typeObj).length - 1]],
        info:
          val !== null
            ? infoObj[val]
            : infoObj[Object.keys(infoObj)[Object.keys(infoObj).length - 1]],
      };
    },
    // 重置数据
    resetForm() {
      this.forms = {};
      this.inventoryNameOption = [];
      this.wareHouseOptions = [];
      // 清空数据
      this.addProductReceiveOrderDetails = [];
      this.$nextTick(() => {
        this.$refs.formsRef && this.$refs.formsRef.clearValidate();
        this.$refs.formsTableRef && this.$refs.formsTableRef.clearValidate();
      });
    },
    handleSelectChange(value, index) {},
    // 选择产品检验单编码弹出选择框，并获取产品检验单编码列表数据
    selectIdChange() {
      this.$refs.selProductInspectionIdRef.dialogVisible = true;
      // 获取产品检验单编码列表数据
      this.queryProductInspectionIdChange();
    },
    // 获取产品检验单编码列表
    async queryProductInspectionIdChange() {
      try {
        this.$refs.selProductInspectionIdRef.loading = true;
        const params = {
          ProductInspectionCode: this.productInspectionCode || "",
          page: this.currentPage,
          rows: this.pageSize,
        };
        const result = await getProductInspectionOrderList(params);
        if (result.status === 0) {
          this.$refs.productInspectionTableRef.tableData = result.rows || [];
          this.totalPage = result.total || 0;
        } else {
          this.$message.error("获取数据失败");
        }
        this.$refs.selProductInspectionIdRef.loading = false;
      } catch (err) {
        console.error("数据异常:", err);
        this.$refs.selProductInspectionIdRef.loading = false;
      }
    },
    // 切换条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.queryProductInspectionIdChange();
    },
    // 切换页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.queryProductInspectionIdChange();
    },
    // 选中的数据
    productInspectionIdSelectionChange(val) {
      this.selectProductInspectionId = val
        ? JSON.parse(JSON.stringify(val))
        : [];
    },
    // 取消 选择产品检验单编码
    closeSelectDocumentChange() {
      this.productInspectionCode = "";
      this.selectProductInspectionId = [];
      this.$refs.productInspectionTableRef.tableData = [];
      this.currentPage = 1;
      this.pageSize = 15;
    },
    // 确认 选择产品检验单编码
    async confirmSelectProductInspectionChange() {
      console.log("选中的数据：", this.selectProductInspectionId);
      if (this.selectProductInspectionId.length === 0) {
        return this.$message.error("请至少选择一行数据");
      }
      if (this.selectProductInspectionId.length != 1) {
        return this.$message.error("只能选择一行数据");
      }
      this.forms.productInspectionCode =
        this.selectProductInspectionId[0].productInspectionCode;
      this.forms.productInspectionId =
        this.selectProductInspectionId[0].productInspectionId;
      // 数据回显
      try {
        this.$refs.selProductInspectionIdRef.loading = true;
        const result = await getProductReceiveOrderInfo(
          this.selectProductInspectionId[0].productInspectionId
        );
        if (result.ok) {
          console.log("单据详情：", result.data);
          this.forms.productInspectionCode =
            result.data.productInspectionCode || "";
          this.forms.productReceiveCode = result.data.productReceiveCode || "";
          if (
            result.data &&
            result.data.productReceiveOrderDetails &&
            result.data.productReceiveOrderDetails.length > 0
          ) {
            this.addProductReceiveOrderDetails =
              result.data.productReceiveOrderDetails.map((item, index) => {
                return {
                  key: index,
                  warehouseId: item.warehouseId,
                  inventoryId: item.inventoryId,
                  quantity: item.quantity,
                };
              });
          }
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (err) {
        console.error("数据异常:", err);
      }
      this.closeSelectDocumentChange();
      this.$refs.selProductInspectionIdRef.dialogVisible = false;
    },
    // 增加行数据
    addRow() {
      let index = this.addProductReceiveOrderDetails.length;
      this.addProductReceiveOrderDetails.push({
        key: index,
        warehouseId: "",
        inventoryId: "",
        quantity: null,
      });
    },
    // 删除行数据
    handleDeleteRow(row) {
      let data = this.addProductReceiveOrderDetails;
      for (var i = 0; i < data.length; i++) {
        if (data[i].key == row.key) {
          data.splice(i, 1);
        }
      }
    },
    confirmChange() {
      if (this.forms.productReceiveId || this.forms.status === 1) {
        const approver = `已经提交的产成品入库单${this.forms.productReceiveCode}不允许修改!`;
        return this.$message.error(approver);
      }
      this.$refs.formsRef.validate((valid) => {
        if (valid) {
          if (this.addProductReceiveOrderDetails.length === 0) {
            this.$message.error("至少添加一行数据");
            return;
          }
          this.$refs.formsTableRef.validate(async (valid2) => {
            if (valid2) {
              this.$emit("pass-verification-change");
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
::v-deep {
  .not-need-form {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper,
  .el-input-number {
    width: 100% !important;
  }
  .el-form-item--default .el-form-item__label {
    height: 32px;
    line-height: 20px !important;
    align-items: center !important;
    text-align: right;
  }
  .el-space {
    width: 100% !important;
  }
  .el-space__item {
    margin-right: 0 !important;
    width: 100% !important;
  }
}
.el-form--inline .el-form-item {
  width: 100% !important;
}
.not-need-form.el-form-item--default {
  margin-bottom: 13px !important;
  margin-top: 13px !important;
}
.demo-ruleForm .el-select {
  width: 100%;
}
.table-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 2px 28px;
  border: 1px solid #eee;
  border-top: 0px;
}
</style>
